package com.example.routelink.gateway.handle;


import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpCookie;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Configuration
@Slf4j
public class KeyConfig {

    @Bean(value = "ipKeyResolver")
    @Primary
    KeyResolver ipKeyResolver() {
        return exchange -> {
            String ip = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress();
            return Mono.just(ip);
        };
    }

    @Bean(value = "userKeyResolver")
    KeyResolver userKeyResolver() {
        return exchange -> {
            HttpCookie user = exchange.getRequest().getCookies().getFirst("user");
            if (user == null) {
                 return Mono.just("default");
            }
            return Mono.just(user.getValue());
        };
    }
}
